package com.nanshenycd.controller.admin;

import com.nanshenycd.pojo.User;
import com.nanshenycd.service.UserService;
import com.nanshenycd.vo.LoginVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Set;

@Controller
@RequestMapping("/admin")
@Api(description  = "后台登录模块接口")
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    //跳转到登录页面
    @RequestMapping
    @ApiOperation(value = "返回查询后的片段信息")
    public String loginPage() {
        return "admin/login";
    }

    //登录
    @PostMapping("/login")
    @ApiOperation(value = "登录判断逻辑接口")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpServletRequest request,
                        HttpServletResponse response,
                        RedirectAttributes attributes
    ) {
        LoginVo loginVo = new LoginVo();
        loginVo.setUsername(username);
        loginVo.setPassword(password);
        User user = userService.doLogin(loginVo, request, response);
        if(null!=user){
            user.setPassword(null);
            attributes.addFlashAttribute("user", user);
//            attributes.addAttribute("user",user);
            return "admin/index";
        }else{
            attributes.addFlashAttribute("message", "用户名或密码错误");
            return "redirect:/admin";
        }
    }
    //注销
    @GetMapping("/logout")
    @ApiOperation(value = "用户注销接口")
    public String logout() {
        Set<String> keys = redisTemplate.keys("user:" + "*");
        redisTemplate.delete(keys);
        System.out.println("模糊删除完成！用户注销所有的分布式session全部删除完成");
        return "redirect:/admin";
    }
}
